package com.github.postsanf.yinian.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.facebook.binaryresource.FileBinaryResource;
import com.facebook.cache.common.SimpleCacheKey;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.YNNativeImage;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.SizeFormat;
import com.github.postsanf.yinian.utils.SnackBarUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.utils.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ImportShareActivitty extends BaseActivity implements View.OnClickListener {
    private int WidthPixels;
    private ImageView btn_share_yinian;
    private ImageView btn_share_wx_timeline;
    private ImageView btn_share_wx_friend;
    private ImageView btn_share_qq_timeline;
    private ImageView btn_share_qq;
    private ProgressDialog mProgressDialog;
    private int groupId;
    private Toolbar mToolbar;
    private Handler handler = new Handler();
    private Map<Integer, Bitmap> mBitmap = new HashMap<>();
    private String shareImgpath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WidthPixels = DisplayUtils.getScreenWidthPixels(this);
        setContentView(R.layout.activity_import_share_activitty);
        initView();
    }

    private void initData() {
        if (SelectedImg.selectedNetPic.size() <= 0) {
            SnackBarUtils.makeShort(mToolbar, "请先选择相片").show();
        } else {
            for (int i = 0; i < SelectedImg.selectedNetPic.size(); i++) {
                Bitmap bitmap = returnBitmap(Uri.parse(SelectedImg.selectedNetPic.get(i).getPath()));
                mBitmap.put(i, bitmap);
            }
            mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_IMG);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Bitmap res = getResPhoto(SelectedImg.selectedNetPic);
                    shareImgpath = saveBitmap(res);
                    mProgressDialog.dismiss();
                }
            }, 200);
        }
    }

    private void initView() {
        mToolbar = ((Toolbar) findViewById(R.id.today_share_toolbar));
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);
        btn_share_yinian = ((ImageView) findViewById(R.id.btn_share_yinian));
        btn_share_wx_timeline = ((ImageView) findViewById(R.id.btn_share_wx_timeline));
        btn_share_wx_friend = ((ImageView) findViewById(R.id.btn_share_wx_friend));
        btn_share_qq_timeline = ((ImageView) findViewById(R.id.btn_share_qq_timeline));
        btn_share_qq = ((ImageView) findViewById(R.id.btn_share_qq));

        btn_share_yinian.setOnClickListener(this);
        btn_share_wx_timeline.setOnClickListener(this);
        btn_share_wx_friend.setOnClickListener(this);
        btn_share_qq_timeline.setOnClickListener(this);
        btn_share_qq.setOnClickListener(this);

        groupId = YNSingleton.getInstance().getCurAlbum().getGroupid();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_share_yinian:
                syncUpImg(false);
                break;
            case R.id.btn_share_wx_timeline:
                if (SelectedImg.selectedNetPic.size() <= 0) {
                    SnackBarUtils.makeShort(mToolbar, "请先选择相片").show();
                } else {
                    for (int i = 0; i < SelectedImg.selectedNetPic.size(); i++) {
                        Bitmap bitmap = returnBitmap(Uri.parse(SelectedImg.selectedNetPic.get(i).getPath()));
                        float scale = (float) bitmap.getHeight() / bitmap.getWidth();
                        Bitmap resPic = resizeImage(bitmap, WidthPixels / 2, (int) (scale * WidthPixels / 2));
                        mBitmap.put(i, resPic);
                    }
                    mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_IMG);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Bitmap res = getResPhoto(SelectedImg.selectedNetPic);
                            shareImgpath = saveBitmap(res);
                            mProgressDialog.dismiss();
                            new ShareAction(ImportShareActivitty.this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                                    .withMedia(new UMImage(ImportShareActivitty.this, res))
                                    .share();
                            Intent statintentfriend = new Intent(ACTIONs.record);
                            statintentfriend.putExtra("key", "backupPhotoFriendCircle_6");
                            statintentfriend.putExtra("value", 1);
                            sendBroadcast(statintentfriend);
                        }
                    }, 200);
                }
                break;
            case R.id.btn_share_wx_friend:
                if (SelectedImg.selectedNetPic.size() <= 0) {
                    SnackBarUtils.makeShort(mToolbar, "请先选择相片").show();
                } else {
                    for (int i = 0; i < SelectedImg.selectedNetPic.size(); i++) {
                        Bitmap bitmap = returnBitmap(Uri.parse(SelectedImg.selectedNetPic.get(i).getPath()));
                        float scale = (float) bitmap.getHeight() / bitmap.getWidth();
                        Bitmap resPic = resizeImage(bitmap, WidthPixels / 2, (int) (scale * WidthPixels / 2));
                        mBitmap.put(i, resPic);
                    }
                    mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_IMG);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Bitmap res = getResPhoto(SelectedImg.selectedNetPic);
                            shareImgpath = saveBitmap(res);
                            mProgressDialog.dismiss();
                            new ShareAction(ImportShareActivitty.this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
                                    .withMedia(new UMImage(ImportShareActivitty.this, res))
                                    .share();
                            Intent statintentfriend = new Intent(ACTIONs.record);
                            statintentfriend.putExtra("key", "backupPhotoWechat_6");
                            statintentfriend.putExtra("value", 1);
                            sendBroadcast(statintentfriend);
                        }
                    }, 200);
                }
                break;
            case R.id.btn_share_qq_timeline:
                if (SelectedImg.selectedNetPic.size() <= 0) {
                    SnackBarUtils.makeShort(mToolbar, "请先选择相片").show();
                } else {
                    for (int i = 0; i < SelectedImg.selectedNetPic.size(); i++) {
                        Bitmap bitmap = returnBitmap(Uri.parse(SelectedImg.selectedNetPic.get(i).getPath()));
                        float scale = (float) bitmap.getHeight() / bitmap.getWidth();
                        Bitmap resPic = resizeImage(bitmap, WidthPixels / 2, (int) (scale * WidthPixels / 2));
                        mBitmap.put(i, resPic);
                    }
                    mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_IMG);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Bitmap res = getResPhoto(SelectedImg.selectedNetPic);
                            shareImgpath = saveBitmap(res);
                            mProgressDialog.dismiss();
                            UMImage image = new UMImage(ImportShareActivitty.this, shareImgpath);
                            UMImage thumb = new UMImage(ImportShareActivitty.this, shareImgpath);
                            image.compressStyle = UMImage.CompressStyle.SCALE;
                            image.setThumb(thumb);
                            new ShareAction(ImportShareActivitty.this).setPlatform(SHARE_MEDIA.QZONE).setCallback(umShareListener)
                                    .withText("分享")
                                    .withMedia(image)
                                    .share();
                            Intent statintentfriend = new Intent(ACTIONs.record);
                            statintentfriend.putExtra("key", "backupPhotoQZone_6");
                            statintentfriend.putExtra("value", 1);
                            sendBroadcast(statintentfriend);
                        }
                    }, 200);
                }
                break;
            case R.id.btn_share_qq:
                if (SelectedImg.selectedNetPic.size() <= 0) {
                    SnackBarUtils.makeShort(mToolbar, "请先选择相片").show();
                } else {
                    for (int i = 0; i < SelectedImg.selectedNetPic.size(); i++) {
                        Bitmap bitmap = returnBitmap(Uri.parse(SelectedImg.selectedNetPic.get(i).getPath()));
                        float scale = (float) bitmap.getHeight() / bitmap.getWidth();
                        Bitmap resPic = resizeImage(bitmap, WidthPixels / 2, (int) (scale * WidthPixels / 2));
                        mBitmap.put(i, resPic);
                    }
                    mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_IMG);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Bitmap res = getResPhoto(SelectedImg.selectedNetPic);
                            shareImgpath = saveBitmap(res);
                            mProgressDialog.dismiss();
                            new ShareAction(ImportShareActivitty.this).setPlatform(SHARE_MEDIA.QQ).setCallback(umShareListener)
                                    .withText("分享")
                                    .withMedia(new UMImage(ImportShareActivitty.this, res))
                                    .share();
                            Intent statintentfriend = new Intent(ACTIONs.record);
                            statintentfriend.putExtra("key", "backupPhotoQQ_6");
                            statintentfriend.putExtra("value", 1);
                            sendBroadcast(statintentfriend);

                        }
                    }, 200);
                }
                break;
        }
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(ImportShareActivitty.this, platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(ImportShareActivitty.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
                finish();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(ImportShareActivitty.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(ImportShareActivitty.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    public void SharePhoto(String photoUri, final Activity activity) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        File file = new File(photoUri);
        shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        shareIntent.setType("image/jpeg");
        startActivity(Intent.createChooser(shareIntent, activity.getTitle()));
    }

    private Bitmap getResPhoto(List<YNNativeImage> urlList) {
        int borderWidth = 6;
        int width = DisplayUtils.getScreenWidthPixels(this) / 2 + borderWidth * 2;
        int height = 0;
        Bitmap resPic = BitmapFactory.decodeResource(getResources(), R.drawable.ic_watermarke);
        Bitmap ic = resizeImage(resPic, width * 2 / 5, (width * 2 / 5 * resPic.getHeight() / resPic.getWidth()));
        for (int i = 0; i < urlList.size(); i++) {
            height += getBitmap(i).getHeight();
        }
        height += (urlList.size() + 1) * borderWidth + borderWidth / 2 + ic.getHeight();
        Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        canvas.drawColor(Color.WHITE);
        int martop = borderWidth;
        for (int i = 0; i < urlList.size(); i++) {
            canvas.drawBitmap(getBitmap(i), borderWidth, martop, null);
            martop += getBitmap(i).getHeight() + borderWidth;
        }
        canvas.drawBitmap(ic, (width - borderWidth - ic.getWidth()), height - borderWidth / 2 - ic.getHeight(), null);

        Paint p = new Paint();
        p.setColor(Color.BLACK);
        p.setAntiAlias(true);   //去除锯齿
        p.setFilterBitmap(true);//对位图进行滤波处理
        p.setTextSize(ic.getHeight() * 2 / 3);
        canvas.drawText("作者:" + application.getCurUser().getUnickname(), borderWidth, height - borderWidth, p);
        return result;
    }

    public Bitmap getBitmap(int position) {
        if (position <= mBitmap.size() - 1) {
            return mBitmap.get(position);
        }
        return null;
    }

    private Bitmap returnBitmap(Uri uri) {

        FileBinaryResource resource = (FileBinaryResource) Fresco.getImagePipelineFactory().getMainDiskStorageCache().getResource(new SimpleCacheKey(uri.toString()));
        File file = resource.getFile();

        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = false;
        newOpts.inPurgeable = true;
        newOpts.inInputShareable = true;

        newOpts.inSampleSize = 2;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        return BitmapFactory.decodeFile(file.getPath(), newOpts);
    }


    //使用Bitmap加Matrix来缩放
    public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
        Bitmap BitmapOrg = bitmap;
        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        int newWidth = w;
        int newHeight = h;

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
                height, matrix, true);
        return resizedBitmap;
    }

    public String saveBitmap(Bitmap bm) {
        File yinianfile = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
        if (!(yinianfile.mkdir() || yinianfile.isDirectory())) {
            yinianfile.mkdirs();
        }
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian/" + System.currentTimeMillis() + ".jpg");
        if (file.exists()) {
            file.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file.toString();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void syncUpImg(boolean isPause) {
        Intent syncIntent = new Intent(ImportShareActivitty.this, ImportPicUploadActivity.class);
        syncIntent.putExtra(ACTIONs.aUid, application.getCurID() + "");
        syncIntent.putExtra(ACTIONs.aGid, groupId + "");
        syncIntent.putExtra(ACTIONs.aType, StringUtils.isOfficialGroup(YNSingleton.getInstance().getCurAlbum().getGtype()) ? 1 : 0);
        syncIntent.putExtra(ACTIONs.aPush, false);
        syncIntent.putExtra(ACTIONs.aIsOfficial, false);
        syncIntent.putExtra(ACTIONs.aGname, YNSingleton.getInstance().getCurAlbum().getGname());
        syncIntent.putExtra(ACTIONs.aContent, "");
        syncIntent.putExtra(ACTIONs.aisPause, isPause);
        syncIntent.putExtra(ACTIONs.upstorage, String.valueOf(SizeFormat.formatDouble(0, SizeFormat.FZ_KB)));
        syncIntent.putExtra(ACTIONs.upismemorycard, 0);
//        startActivityForResult(syncIntent, TAKE_SYNC);
        startActivity(syncIntent);
    }

    @Override
    protected void onDestroy() {
        SelectedImg.selectedNetPic.clear();
        mBitmap.clear();
        System.gc();
        super.onDestroy();
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
